//
//  SAWarehousingVC.m
//  saasRetail
//
//  Created by 黄志刚 on 2021/5/13.
//

#import "SAWarehousingVC.h"
#import "SAWarehousingSelectShopVC.h"
#import "ScanHelper.h"
#import "SACommodityWarehousingCell.h"
#import "SASalesOrderViewListModel.h"
#import "HDDatePickerView.h"
#import "SASearchStoreUserView.h"
#import "SASearchSupplierView.h"
#import "SAInputDiscountView.h"
#import "SASystemSettingsListAPI.h"
#import "UILabel+NSMutableAttributedString.h"
#import "SAPayView.h"
#import "SASalesSaveAPI.h"
#import "SAWarehousingDocumentsVC.h"
#import "SACommodityWarehousingHeaderView.h"
#import "SAWarehousePurchaseSaveAPI.h"
#import "SASystemEmpDetailAPI.h"
#import "SAStoreUserModel.h"
#import "SASupplierModel.h"
#import "SACommodityAddShopSizeView.h"
#import "YBImageBrowser.h"
#import "SAWarehousePurchaseFindProductAPI2.h"
#import "SAWarehousePurchaseFindProductV2API.h"
#import "SASalesOrderStatementErrorView.h"
#import "SASalesOrderStatementErrorModel.h"
#import "NSString+nonce.h"
#import "NSString+MD5.h"

@interface SAWarehousingVC ()<UITableViewDataSource, UITableViewDelegate, HTTPAPIDelegate, UITextFieldDelegate,YBImageBrowserDataSource>

@property (nonatomic, strong) UIButton *empBtn;
@property (nonatomic, strong) UIButton *dateBtn;
@property (nonatomic, strong) UIButton *vipBtn;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) float tableViewTop;
@property (nonatomic, strong) NSMutableArray<SASalesOrderViewListModel *> *dataMarr;
@property (nonatomic, strong) UIView *footView;

@property (nonatomic, strong) UIButton *scanBtn;
@property (nonatomic, strong) UIButton *addBtn;
@property (nonatomic, assign) BOOL isVip;
@property (nonatomic, strong) SASearchStoreUserView *searchStoreUserView;
@property (nonatomic, strong) SASearchSupplierView *searchSupplierView;
@property (nonatomic, strong) SASupplierModel *supplierModel;
@property (nonatomic, strong) SAStoreUserModel *userModel;

@property (nonatomic, strong) SASystemSettingsListAPI *systemSettingsListAPI;
@property (nonatomic, strong) UITextField *discountTf;
@property (nonatomic, strong) NSString *discount;
@property (nonatomic, strong) NSString *limit;
@property (nonatomic, strong) UILabel *shopLab;
@property (nonatomic, strong) UILabel *shopPirceLab;
@property (nonatomic, strong) UILabel *integralLab;
@property (nonatomic, strong) UILabel *totalCountLab;
@property (nonatomic, strong) SASalesSaveAPI *salesSaveAPI;
@property (nonatomic, strong) UIView *headerView;

@property (nonatomic, strong) UIView *moreView;
@property (nonatomic, strong) UIButton *selectBtn;
@property (nonatomic, strong) SAWarehousePurchaseSaveAPI *warehousePurchaseSaveAPI;
@property (nonatomic, strong) SASystemEmpDetailAPI *systemEmpDetailAPI;
@property (nonatomic, strong) UITextField *remarkTf;
@property (nonatomic, strong) UIButton *cancelBtn;
@property (nonatomic, strong) NSArray *imageList;
@property (nonatomic, strong) SAWarehousePurchaseFindProductAPI2 *warehousePurchaseFindProductAPI;
@property (nonatomic, strong) SAWarehousePurchaseFindProductV2API *warehousePurchaseFindProductV2API;
@property (nonatomic, strong) UIButton *payTypeBtn;

@property (nonatomic, assign) BOOL isWarehousingStock;//yes可以负数入库 no不可以负数入库
@property (nonatomic, strong) UIButton *settlementBtn;
@property (nonatomic, assign) double totalCount;
@property (nonatomic, strong) NSString *randomStr;

@end

@implementation SAWarehousingVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    if (self.systemSettingsListAPI == api) {
        NSArray *arr = data[@"data"][@"member_points_setting"][@"childSettings"];
        NSString *discount = @"0";
        NSString *limit = @"0";
        for (NSDictionary *dic in arr) {
            NSString *settingsId = dic[@"settingsId"];
            if ([settingsId isEqualToString:@"45"]) {
                discount = dic[@"value"];
            }
            if ([settingsId isEqualToString:@"46"]) {
                limit = dic[@"value"];
            }
        }
        NSString *negative = data[@"data"][@"negative_stock_in"][@"value"];
        if ([negative isEqualToString:@"1"]) {
            self.isWarehousingStock = YES;
        }else {
            self.isWarehousingStock = NO;
        }
//        self.discount = discount;
//        self.limit = limit;
//        if ([self.limit integerValue] > 0) {
//            self.discountTf.userInteractionEnabled = YES;
//        }else {
//            self.discountTf.userInteractionEnabled = NO;
//        }
//        self.discountTf.placeholder = [NSString stringWithFormat:@"%0.f可抵:%@元",[discount doubleValue] *  [limit doubleValue],limit];
    }else if (self.systemEmpDetailAPI == api) {
        self.userModel = [SAStoreUserModel mj_objectWithKeyValues:data[@"data"]];
    }else if (self.warehousePurchaseSaveAPI == api) {
        [self.dataMarr removeAllObjects];
        [self.tableView reloadData];
        [self upData];
        [self setBottomUI];
        [self clickedCancelBtn];
        self.remarkTf.text = @"";
        [Prompt popPromptViewWithMsg:@"结账成功" duration:2];
        
        !self.refreshBlock ?: self.refreshBlock();
    }else if (self.warehousePurchaseFindProductAPI == api) {
        WeakSelf
        NSMutableArray *marr = [SASalesOrderViewListModel mj_objectArrayWithKeyValuesArray:data[@"data"]];
        if (marr.count == 1) {
            SASalesOrderViewListModel *model = marr[0];
            
            //如果扫码且只有一个颜色尺码则直接加1处理
            if ([self.warehousePurchaseFindProductAPI.barCodeSign isEqualToString:@"true"]) {
                if (model.targetSkuList.count == 1) {
                    NSString *skuId = model.targetSkuList[0].skuId;
                    model.targetSkuList = [NSMutableArray array];
                    for (SASalesOrderToPendSkuList *list in model.toPendSkuAttrs) {
                        if ([list.skuId isEqualToString:skuId]) {
                            list.inventoryCount = [NSString stringWithFormat:@"%@",list.count];
                            list.count = @"0";
                            SASalesOrderToPendSkuList *newList = [SASalesOrderToPendSkuList new];
                            list.stock = list.count;
                            
                            newList.colourId = list.colourId;
                            newList.colourName = list.colourName;
                            newList.sizeId = list.sizeId;
                            newList.sizeName = list.sizeName;
                            newList.stock = @"1";
                            newList.count = list.count;
                            newList.skuId = list.skuId;
                            newList.price = model.retailPrice;
                            newList.inventoryCount = list.inventoryCount;
                            [model.targetSkuList addObject:newList];
                        }
                    }
                    [self combinationData:model];
                    [self.tableView reloadData];
                    [self upData];
                    [self setBottomUI];
                    return;
                }
            }
            
            model.targetSkuList = [NSMutableArray array];
            for (SASalesOrderToPendSkuList *list in model.toPendSkuAttrs) {
                list.inventoryCount = [NSString stringWithFormat:@"%@",list.count];
                list.count = @"0";
                SASalesOrderToPendSkuList *newList = [SASalesOrderToPendSkuList new];
                list.stock = list.count;
                
                newList.colourId = list.colourId;
                newList.colourName = list.colourName;
                newList.sizeId = list.sizeId;
                newList.sizeName = list.sizeName;
                newList.stock = @"0";
                newList.count = list.count;
                newList.skuId = list.skuId;
                newList.inventoryCount = list.inventoryCount;
                [model.targetSkuList addObject:newList];
            }
            
            SACommodityAddShopSizeView *addShopSizeView = [[SACommodityAddShopSizeView alloc] initWithListModel:model];
            addShopSizeView.isAll = YES;
            addShopSizeView.isWarehousingStock = self.isWarehousingStock;
            [addShopSizeView showView:self];
            addShopSizeView.showImageBlock = ^{
                [weakSelf showImage:model.imgList];
            };
            addShopSizeView.selectBlock = ^(SASalesOrderViewListModel * _Nonnull model) {
                model.targetSkuList = [NSMutableArray array];
                for (SASalesOrderToPendSkuList *list in model.toPendSkuAttrs) {
                    if ([list.stock doubleValue] != 0) {
                        [model.targetSkuList addObject:list];
                    }
                }
                if (model.targetSkuList.count == 0) {
                    return;
                }
                [weakSelf combinationData:model];
                [weakSelf.tableView reloadData];
                [weakSelf upData];
                [weakSelf setBottomUI];
            };
        }else {
            [Prompt popPromptViewWithMsg:@"未查询到商品" duration:2];
        }
    }else if (self.warehousePurchaseFindProductV2API == api) {
        WeakSelf
        NSMutableArray *marr = [SASalesOrderViewListModel mj_objectArrayWithKeyValuesArray:data[@"data"]];
        if (marr.count == 1) {
            SASalesOrderViewListModel *model = marr[0];
            
            model.targetSkuList = [NSMutableArray array];
            for (SASalesOrderToPendSkuList *list in model.toPendSkuAttrs) {
                list.inventoryCount = [NSString stringWithFormat:@"%@",list.count];
                list.count = @"0";
                SASalesOrderToPendSkuList *newList = [SASalesOrderToPendSkuList new];
                list.stock = list.count;
                
                newList.colourId = list.colourId;
                newList.colourName = list.colourName;
                newList.sizeId = list.sizeId;
                newList.sizeName = list.sizeName;
                newList.stock = @"0";
                newList.count = list.count;
                newList.skuId = list.skuId;
                newList.inventoryCount = list.inventoryCount;
                [model.targetSkuList addObject:newList];
            }
            
            SACommodityAddShopSizeView *addShopSizeView = [[SACommodityAddShopSizeView alloc] initWithListModel:model];
            addShopSizeView.isAll = YES;
            addShopSizeView.isWarehousingStock = self.isWarehousingStock;
            [addShopSizeView showView:self];
            addShopSizeView.showImageBlock = ^{
                [weakSelf showImage:model.imgList];
            };
            addShopSizeView.selectBlock = ^(SASalesOrderViewListModel * _Nonnull model) {
                model.targetSkuList = [NSMutableArray array];
                for (SASalesOrderToPendSkuList *list in model.toPendSkuAttrs) {
                    if ([list.stock doubleValue] != 0) {
                        [model.targetSkuList addObject:list];
                    }
                }
                [weakSelf combinationData:model];
                [weakSelf.tableView reloadData];
                [weakSelf upData];
                [weakSelf setBottomUI];
            };
        }else {
            [Prompt popPromptViewWithMsg:@"未查询到商品" duration:2];
        }
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
    if (self.warehousePurchaseSaveAPI == api) {
        NSDictionary *dict = error.userInfo;
        if ([[NSString stringWithFormat:@"%@",dict[@"code"]] isEqualToString:@"20007"]) {
            NSDictionary *errorDic = [self dictionaryWithJsonString:dict[@"msg"]];
            NSMutableArray *errorArray = [NSMutableArray array];
            for (NSArray *errorLsit in errorDic) {
                SASalesOrderStatementErrorModel *model = [SASalesOrderStatementErrorModel mj_objectWithKeyValues:errorLsit];
                NSLog(@"%@",model);
                [errorArray addObject:model];
            }
            
            SASalesOrderStatementErrorView *screenView = [SASalesOrderStatementErrorView shareCornView];
            screenView.removeBlock = ^(NSArray * _Nonnull array) {
                for (SASalesOrderViewListModel *model in self.dataMarr) {
                    for (SASalesOrderToPendSkuList *skuList in [model.targetSkuList reverseObjectEnumerator]) {
                        for (SASalesOrderStatementErrorSkuList *errorList in array) {
                            if ([errorList.skuId isEqualToString:skuList.skuId]) {
                                [model.targetSkuList removeObject:skuList];
                                break;
                            }
                        }
                    }
                }
                
                NSMutableArray *newDataArray = [NSMutableArray array];
                for (SASalesOrderViewListModel *listModel in self.dataMarr) {
                    if (listModel.targetSkuList.count > 0) {
                        [newDataArray addObject:listModel];
                    }
                }
                self.dataMarr = newDataArray;
                [self upData];
                [self setBottomUI];
                [self.tableView reloadData];
            };
            [screenView loadData:errorArray];
            [screenView showView:nil];
        }else if ([[NSString stringWithFormat:@"%@",dict[@"code"]] isEqualToString:@"50001"]) {
            NSString *msg = dict[@"msg"];
            [Prompt popPromptViewWithMsg:msg duration:3];
            [self clickedCancelBtn];
        }else if ([[NSString stringWithFormat:@"%@",dict[@"code"]] isEqualToString:@"50002"]) {
            NSString *msg = dict[@"msg"];
            [Prompt popPromptViewWithMsg:msg duration:3];
            [self clickedCancelBtn];
        }else {
            NSString *msg = dict[@"msg"];
            [Prompt popPromptViewWithMsg:msg duration:3];
        }
    }
}

#pragma mark - UITableView Delegate & DataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataMarr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataMarr[section].targetSkuList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WeakSelf
    SACommodityWarehousingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SACommodityWarehousingCell" forIndexPath:indexPath];
    cell.isWarehousingStock = self.isWarehousingStock;
    SASalesOrderToPendSkuList *model = self.dataMarr[indexPath.section].targetSkuList[indexPath.row];
    cell.model = model;
    cell.inputBlock = ^(NSString * _Nonnull str) {
        model.stock = str;
        [weakSelf upData];
    };
    cell.addBlock = ^{
        NSInteger stock = [model.stock integerValue] + 1;
        model.stock = [NSString stringWithFormat:@"%zd",stock];
        [weakSelf upData];
    };
    cell.cutBlock = ^{
        NSInteger stock = [model.stock integerValue] - 1;
        model.stock = [NSString stringWithFormat:@"%zd",stock];
        [weakSelf upData];
    };
    cell.inputPriceBlock = ^(NSString * _Nonnull str) {
        model.price = [NSString stringWithFormat:@"%0.2f",[str doubleValue] * 100];
        [weakSelf upData];
    };
    cell.deleteBlock = ^{

    };
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kScaleNum(35);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == self.dataMarr.count) {
        return [[UIView alloc] initWithFrame:CGRectZero];
    }
    SACommodityWarehousingHeaderView *headerView = [[SACommodityWarehousingHeaderView alloc] initWithReuseIdentifier:@"SACommodityWarehousingHeaderView"];
    __block SASalesOrderViewListModel *dataModel = self.dataMarr[section];
    headerView.model = dataModel;
    WeakSelf
    headerView.deleteBlock = ^{
        [weakSelf.dataMarr removeObject:dataModel];
        [tableView reloadData];
        [weakSelf upData];
        [weakSelf setBottomUI];
    };
    headerView.addBlock = ^{
        weakSelf.warehousePurchaseFindProductV2API.productIds = dataModel.productId;
        [weakSelf.warehousePurchaseFindProductV2API sendRequestToServerWithActivityViewAndMask:GET];
    };
    return headerView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == self.dataMarr.count) {
        return kScaleNum(0.01);
    }
    return kScaleNum(35);
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return kScaleNum(1);
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

-(NSArray<UITableViewRowAction*>*)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    SASalesOrderViewListModel *model = self.dataMarr[indexPath.section];
    SASalesOrderToPendSkuList *list = model.targetSkuList[indexPath.row];
    WeakSelf
    UITableViewRowAction *rowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault
                                                                         title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        if (model.targetSkuList.count == 1) {
            [weakSelf.dataMarr removeObject:model];
            [tableView reloadData];
            [weakSelf upData];
            [weakSelf setBottomUI];
        }else {
            [model.targetSkuList removeObject:list];
            [tableView reloadData];
            [weakSelf upData];
            [weakSelf setBottomUI];
        }
        
    }];
    rowAction.backgroundColor = kPinkColor;
    NSArray *arr = @[rowAction];
    return arr;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}

#pragma mark - UITextFieldDelegate

#pragma mark - event
-(void)clickedScanBtn {
    [self.view endEditing:YES];
    [self.navigationController pushViewController:[[ScanHelper shareInstance] ScanVCWithStyle:notSquare qrResultCallBack:^(id result) {
        self.warehousePurchaseFindProductAPI.barCodeSign = @"true";
        self.warehousePurchaseFindProductAPI.productCodeOrBar = result;
        [self.warehousePurchaseFindProductAPI sendRequestToServerWithActivityViewAndMask:GET];
        [self.navigationController popViewControllerAnimated:NO];
    }] animated:YES];
}

-(void)clickedAddBtn {
    [self.view endEditing:YES];
    SAWarehousingSelectShopVC *shopVC = [[SAWarehousingSelectShopVC alloc] initWithSelectMarr:[NSMutableArray array]];
    shopVC.isWarehousingStock = self.isWarehousingStock;
    [self.navigationController pushViewController:shopVC animated:YES];
    WeakSelf
    shopVC.selectBlock = ^(NSMutableArray<SASalesOrderViewListModel *> * _Nonnull selectMarr) {
        for (SASalesOrderViewListModel *model in selectMarr) {
            model.targetSkuList = [NSMutableArray array];
            for (SASalesOrderToPendSkuList *list in model.toPendSkuAttrs) {
                if ([list.stock doubleValue] != 0) {
                    [model.targetSkuList addObject:list];
                }
            }
            [weakSelf combinationData:model];
        }
        
    };
}

-(void)combinationData:(SASalesOrderViewListModel *)model {
    BOOL newProduct = YES;
    SASalesOrderViewListModel *oldModel = nil;
    for (SASalesOrderViewListModel *listModel in self.dataMarr) {
        if ([listModel.productId isEqualToString:model.productId]) {
            oldModel = listModel;
            newProduct = NO;
            break;
        }
    }
    if (newProduct) {
        for (SASalesOrderToPendSkuList *skuModel in model.targetSkuList) {
            if ([skuModel.stock integerValue] < 0) {
                skuModel.type = 1;
            }else {
                skuModel.type = 0;
            }
        }
        [self.dataMarr addObject:model];
    }else {
        for (SASalesOrderToPendSkuList *skuModel in oldModel.targetSkuList) {
            if ([skuModel.stock integerValue] < 0) {
                skuModel.type = 1;
            }else {
                skuModel.type = 0;
            }
        }
        for (SASalesOrderToPendSkuList *skuModel in model.targetSkuList) {
            if ([skuModel.stock integerValue] < 0) {
                skuModel.type = 1;
            }else {
                skuModel.type = 0;
            }
            BOOL newSku = YES;
            for (SASalesOrderToPendSkuList *model2 in oldModel.targetSkuList) {
                if ([skuModel.skuId isEqualToString:model2.skuId] && skuModel.type == model2.type) {
                    newSku = NO;
                    model2.stock = [NSString stringWithFormat:@"%zd",[model2.stock integerValue] + [skuModel.stock integerValue]];
                    break;
                }
            }
            if (newSku) {
                [oldModel.targetSkuList addObject:skuModel];
            }
        }
    }
    [self upData];
    [self setBottomUI];
}

//入库单据
-(void)clickedListBtn {
    [self.view endEditing:YES];
    
    NSMutableArray *menuList = [SAValueManger shareInStance].userInfo.menuList;
    NSString *purchaseReceipt = [NSString stringWithFormat:@"%@",menuList[2][@"perms"][@"purchaseReceipt"]];
    if ([purchaseReceipt isEqualToString:@"1"]) {
        [Prompt popPromptViewWithMsg:@"您没有入库单据权限,请联系店长添加" duration:2];
        return;;
    }
    
    SAWarehousingDocumentsVC *pushVC = [SAWarehousingDocumentsVC new];
    [self.navigationController pushViewController:pushVC animated:YES];
}

//防止多次结单
- (void)unisversalButtonAcrion:(UIButton *)sender
{
    sender.userInteractionEnabled = NO;
    [[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(clickedSettlementBtn) object:sender];
    [self performSelector:@selector(clickedSettlementBtn) withObject:sender afterDelay:0.3f];
}

-(void)clickedSettlementBtn {
    [self.view endEditing:YES];
    NSMutableDictionary *mdic = [NSMutableDictionary dictionary];
    NSMutableArray *payAddFormArray = [[NSMutableArray alloc] init];
    NSMutableArray *detailFormArray = [[NSMutableArray alloc] init];
    
    NSMutableDictionary *pendAddForm = [NSMutableDictionary dictionary];
    pendAddForm[@"actualPrice"] = @"0";
    pendAddForm[@"empId"] = self.userModel.empId;
    pendAddForm[@"empName"] = self.userModel.empName;
    pendAddForm[@"isBalance"] = @"0";
    pendAddForm[@"purchaseTime"] = self.dateBtn.titleLabel.text;
    pendAddForm[@"remark"] = self.remarkTf.text;
    pendAddForm[@"shouldPrice"] = [NSString stringWithFormat:@"%0.lf",self.totalCount * 100];
    if (self.isVip == YES) {
        pendAddForm[@"providerId"] = self.supplierModel.providerId;
        pendAddForm[@"providerName"] = self.supplierModel.providerName;
    }
    [mdic setValue:pendAddForm forKey:@"pendAddForm"];
    
    NSMutableDictionary *payAddFormDic = [[NSMutableDictionary alloc] init];
    payAddFormDic[@"payType"] = [NSString stringWithFormat:@"%zd",self.selectBtn.tag];
    payAddFormDic[@"payPrice"] = [NSString stringWithFormat:@"%0.lf",self.totalCount * 100];
    [payAddFormArray addObject:payAddFormDic];
    mdic[@"payAddForm"] = payAddFormArray;
    
    for (SASalesOrderViewListModel *model in self.dataMarr) {
        for (SASalesOrderToPendSkuList *skuList in model.targetSkuList) {
            if ([skuList.stock integerValue] == 0) {
                [Prompt popPromptViewWithMsg:@"数量不符合要求,请重新核对" duration:2];
                self.settlementBtn.userInteractionEnabled = YES;
                return;
            }
            if (skuList.noPirce == YES) {
                [Prompt popPromptViewWithMsg:@"单价不符合要求,请重新核对" duration:2];
                self.settlementBtn.userInteractionEnabled = YES;
                return;
            }
            if ([skuList.stock integerValue] < 0) {
                if (self.supplierModel.providerId.length == 0) {
                    [Prompt popPromptViewWithMsg:@"有退货请先选择供货商" duration:2];
                    self.settlementBtn.userInteractionEnabled = YES;
                    return;
                }
            }
            NSMutableDictionary *detailFormDic = [[NSMutableDictionary alloc] init];
            detailFormDic[@"count"] = skuList.stock;
            detailFormDic[@"price"] = [NSString stringWithFormat:@"%0.f",[skuList.price doubleValue]];
            detailFormDic[@"productCode"] = model.productCode;
            detailFormDic[@"productId"] = model.productId;
            detailFormDic[@"productName"] = model.productName;
            detailFormDic[@"remark"] = @"";
            detailFormDic[@"returnsExceedCount"] = @"0";
            detailFormDic[@"skuId"] = skuList.skuId;
            [detailFormArray addObject:detailFormDic];
        }
    }
    mdic[@"detailAddForm"] = detailFormArray;
    
    NSData *nData = [NSJSONSerialization dataWithJSONObject:mdic options:0 error:nil];
    mdic[@"randomStr"] = [NSString stringWithFormat:@"%@%@",self.randomStr,[NSString getMD5WithData:nData]];
    
    self.warehousePurchaseSaveAPI.coverParameters = mdic;
    [self.warehousePurchaseSaveAPI sendRequestToServerWithActivityViewAndMask:POST];
    self.settlementBtn.userInteractionEnabled = YES;
}

-(void)clickedUserBtn {
    [self.view endEditing:YES];
    SASearchStoreUserView *searchStoreUserView = [SASearchStoreUserView shareCornView];
    UIViewController *vc = nil;
    [searchStoreUserView showView:vc];
    WeakSelf
    searchStoreUserView.selectBlock = ^(SAStoreUserModel * _Nonnull userModel) {
        weakSelf.userModel = userModel;
        if (userModel.mobile.length > 0) {
            [weakSelf.empBtn setTitle:[NSString stringWithFormat:@"%@(%@)",userModel.empName,userModel.mobile] forState:UIControlStateNormal];
        }else {
            [weakSelf.empBtn setTitle:[NSString stringWithFormat:@"%@",userModel.empName] forState:UIControlStateNormal];
        }
        CGFloat imageWidth = weakSelf.empBtn.imageView.bounds.size.width;
        CGFloat labelWidth = weakSelf.empBtn.titleLabel.bounds.size.width;
        weakSelf.empBtn.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth);
        weakSelf.empBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWidth-10, 0, imageWidth + 10);
        [weakSelf.empBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
    };
}

-(void)clickedDateBtn {
    WeakSelf
    [self.view endEditing:YES];
    HDDatePickerView *pickerView = [[HDDatePickerView alloc] initWithSlectedDate:self.dateBtn.titleLabel.text];
    [pickerView show];
    pickerView.selectDateBlock = ^(NSString *selectedDate) {
        [weakSelf.dateBtn setTitle:selectedDate forState:UIControlStateNormal];
    };
}

-(void)clickedVipBtn {
    [self.view endEditing:YES];
    NSMutableArray *menuList = [SAValueManger shareInStance].userInfo.menuList;
    NSString *isSupplier = [NSString stringWithFormat:@"%@",menuList[7][@"isDelete"]];
    NSString *seeProvider = [NSString stringWithFormat:@"%@",menuList[7][@"perms"][@"seeProvider"]];
    if ([isSupplier isEqualToString:@"1"]) {
        [Prompt popPromptViewWithMsg:@"您没有供货商权限,请联系店长添加" duration:2];
        return;
    }
    if ([seeProvider isEqualToString:@"1"]) {
        [Prompt popPromptViewWithMsg:@"您没有供货商权限,请联系店长添加" duration:2];
        return;
    }
    SASearchSupplierView *searchSupplierView = [SASearchSupplierView shareCornView];
    searchSupplierView.isWarehousing = YES;
    UIViewController *vc = nil;
    [searchSupplierView showView:vc];
    WeakSelf
    searchSupplierView.selectBlock = ^(SASupplierModel * _Nonnull supplierModel) {
        if (supplierModel.mobile.length > 0) {
            [weakSelf.vipBtn setTitle:[NSString stringWithFormat:@"%@(%@)",supplierModel.providerName,supplierModel.mobile] forState:UIControlStateNormal];
        }else {
            [weakSelf.vipBtn setTitle:supplierModel.providerName forState:UIControlStateNormal];
        }
        
        [weakSelf.vipBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
        [weakSelf.vipBtn setImage:[UIImage imageNamed:@"Sale_rightArrow"] forState:UIControlStateNormal];
        CGFloat imageWidth = weakSelf.vipBtn.imageView.bounds.size.width;
        CGFloat labelWidth = weakSelf.vipBtn.titleLabel.bounds.size.width;
        weakSelf.vipBtn.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth);
        weakSelf.vipBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWidth-10, 0, imageWidth + 10);
        weakSelf.supplierModel = supplierModel;
        weakSelf.isVip = YES;
        weakSelf.cancelBtn.hidden = NO;
    };
}

-(void)clickedCancelBtn {
    [self.view endEditing:YES];
    self.cancelBtn.hidden = YES;
    self.isVip = NO;
    self.supplierModel = nil;
    [self.vipBtn setTitle:@"请选供货商" forState:UIControlStateNormal];
    [self.vipBtn setTitleColor:kColor(200, 200, 200, 1) forState:UIControlStateNormal];
    CGFloat imageWidth = self.vipBtn.imageView.bounds.size.width;
    CGFloat labelWidth = self.vipBtn.titleLabel.bounds.size.width;
    self.vipBtn.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth);
    self.vipBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWidth-10, 0, imageWidth + 10);
    self.randomStr = [NSString random:10];
}

-(void)clickedPayBtn:(UIButton *)sender {
    self.moreView.hidden = YES;
    self.selectBtn.selected = NO;
    self.selectBtn = sender;
    self.selectBtn.selected = YES;
    if (sender.tag == 1) {
        [self.payTypeBtn setTitle:@"现金" forState:UIControlStateNormal];
    }else if (sender.tag == 2){
        [self.payTypeBtn setTitle:@"刷卡" forState:UIControlStateNormal];
    }else if (sender.tag == 3){
        [self.payTypeBtn setTitle:@"汇款" forState:UIControlStateNormal];
    }else if (sender.tag == 4){
        [self.payTypeBtn setTitle:@"微信" forState:UIControlStateNormal];
    }else if (sender.tag == 5){
        [self.payTypeBtn setTitle:@"支付宝" forState:UIControlStateNormal];
    }
    CGFloat imageWidth = self.payTypeBtn.imageView.bounds.size.width;
    CGFloat labelWidth = self.payTypeBtn.titleLabel.bounds.size.width;
    self.payTypeBtn.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth);
    self.payTypeBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWidth-10, 0, imageWidth + 10);
}

-(void)removeView {
    self.moreView.hidden = YES;
}

-(void)showPayTypeView {
    self.moreView.hidden = NO;
}

-(void)upData {
    if (self.dataMarr.count > 0) {
        NSInteger num = 0;
        double total = 0;
        for (SASalesOrderViewListModel *model in self.dataMarr) {
            for (SASalesOrderToPendSkuList *list in model.targetSkuList) {
                NSString *price = [NSString stringWithFormat:@"%0.2lf",[list.price doubleValue]/100.f];
                total += [list.stock integerValue] * [price doubleValue];
                num += [list.stock integerValue];
            }
        }
        self.shopLab.text = [NSString stringWithFormat:@"选择商品(%zd)",num];
        self.shopLab.textColor = kBlackColor;
        [self.shopLab setAttributedStringWithSubString:[NSString stringWithFormat:@"%zd",num] color:kPinkColor];
        self.shopPirceLab.text = [NSString stringWithFormat:@"￥%0.2f",total];
        self.totalCountLab.text = [NSString stringWithFormat:@"%0.2f",total];
        self.totalCount = total;
        
        NSString *productViewCostPrice = [NSString stringWithFormat:@"%@",[SAValueManger shareInStance].userInfo.menuList[1][@"perms"][@"productViewCostPrice"]];
        if ([productViewCostPrice isEqualToString:@"1"]) {
            self.shopPirceLab.text = @"￥******";
            self.totalCountLab.text = @"******";
        }
        
    }else {
        self.shopLab.text = @"选择商品";
        self.shopLab.textColor = kBlackColor;
        self.shopPirceLab.text = @"";
        self.totalCountLab.text = @"";
    }
}

-(void)setBottomUI {
    if (self.dataMarr.count > 0) {
        self.footView.hidden = NO;
        self.tableView.tableHeaderView = self.headerView;
            self.scanBtn.frame = CGRectMake(kScaleNum(76), kScreenHeight - kScaleNum(163) - SafeFooterHeight, kScaleNum(53), kScaleNum(52));
            self.addBtn.frame = CGRectMake(kScreenWidth - kScaleNum(120), kScreenHeight - kScaleNum(163) - SafeFooterHeight, kScaleNum(53), kScaleNum(52));
    }else {
        self.footView.hidden = YES;
        self.scanBtn.frame = CGRectMake(kScaleNum(76),  self.tableViewTop + kScaleNum(10), kScaleNum(53), kScaleNum(52));
        self.addBtn.frame = CGRectMake(kScreenWidth - kScaleNum(120), self.tableViewTop + kScaleNum(10), kScaleNum(53), kScaleNum(52));
    }
    self.tableView.frame = CGRectMake(0, self.tableViewTop, kScreenWidth, self.scanBtn.y - self.tableViewTop - kScaleNum(8));
    [self.tableView reloadData];
}

-(void)showImage:(NSArray *)imageList {
    self.imageList = imageList;
    if (self.imageList.count > 0) {
        NSMutableArray *imageMarr = [NSMutableArray array];
        for (NSString *url in self.imageList) {
            NSString *newUrl = [url stringByReplacingOccurrencesOfString:@"?x-oss-process=style/thumbnail" withString:@""];
            NSString *imageUrl = [NSString stringWithFormat:@"%@?x-oss-process=image/resize,l_720",newUrl];
            [imageMarr addObject:imageUrl];
        }
        self.imageList = imageMarr;
        YBImageBrowser *browser = [YBImageBrowser new];
        browser.dataSourceArray = self.imageList;
        browser.dataSource = self;
        browser.currentPage = 0;
        [browser show];
    }else {
        [Prompt popPromptViewWithMsg:@"该商品没有图片" duration:2];
    }
}

//YBImageBrowserDataSource 代理实现赋值数据
- (NSInteger)yb_numberOfCellsInImageBrowser:(YBImageBrowser *)imageBrowser {
    return self.imageList.count;
}

- (id<YBIBDataProtocol>)yb_imageBrowser:(YBImageBrowser *)imageBrowser dataForCellAtIndex:(NSInteger)index {
    NSString *urlStr = [self.imageList objectAtIndex:index];
    YBIBImageData *data = [YBIBImageData new];
    data.imageURL = [NSURL URLWithString:urlStr];
    return data;
}

#pragma mark - initUI
-(void)initUI {
    [self setNavigationItemBackBBIAndTitle:@"商品入库"];
    [self setBgImage:nil];
    self.randomStr = [NSString random:10];
    
    UIButton *listBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    listBtn.frame = CGRectMake(0, 0, kScaleNum(60), kScaleNum(44));
    [listBtn setImage:[UIImage imageNamed:@"shopSale_list"] forState:UIControlStateNormal];
    [listBtn addTarget:self action:@selector(clickedListBtn) forControlEvents:UIControlEventTouchUpInside];
    [self addRightViews:@[listBtn]];
    
    self.view.backgroundColor = kBgColor;
    
    UIView *whiteView = [[UIView alloc] initWithFrame:SARectMake(0, StatusHeight, kBaseScreenWidth, 151)];
    whiteView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:whiteView];
    
    SAUserInfo *model = [SAValueManger shareInStance].userInfo;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *timeFormatStr = [dateFormatter stringFromDate:[NSDate date]];
    
    NSArray *nameArr = @[@"  店员", @"  日期", @"  供货商", @"  备注"];
    NSArray *imageArr = @[@"Sale_user", @"Sale_clock", @"Warehousing_icon_1", @"Warehousing_icon_5"];
    for (int i = 0; i < nameArr.count; i++) {
        UIButton *titleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [titleBtn setImage:[UIImage imageNamed:imageArr[i]] forState:UIControlStateNormal];
        [titleBtn setTitle:nameArr[i] forState:UIControlStateNormal];
        titleBtn.frame = SARectMake(20, StatusHeight + i * 38, 120, 37);
        titleBtn.titleLabel.font = kFont(15);
        [titleBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
        titleBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [self.view addSubview:titleBtn];
        
        if (i < 3) {
            UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [rightBtn setImage:[UIImage imageNamed:@"Sale_rightArrow"] forState:UIControlStateNormal];
            rightBtn.frame = SARectMake(0, StatusHeight + i * 38, kBaseScreenWidth - 20, 37);
            rightBtn.titleLabel.font = kFont(15);
            [rightBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
            rightBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
            [self.view addSubview:rightBtn];
            if (i == 0) {
                [rightBtn setTitle:[NSString stringWithFormat:@"%@(%@)",model.empName,model.mobile] forState:UIControlStateNormal];
                [rightBtn addTarget:self action:@selector(clickedUserBtn) forControlEvents:UIControlEventTouchUpInside];
                self.empBtn = rightBtn;
            }else if (i == 1) {
                [rightBtn setTitle:timeFormatStr forState:UIControlStateNormal];
                self.dateBtn = rightBtn;
                [rightBtn addTarget:self action:@selector(clickedDateBtn) forControlEvents:UIControlEventTouchUpInside];
            }else if (i == 2){
                [rightBtn setTitle:@"请选择供货商" forState:UIControlStateNormal];
                [rightBtn setTitleColor:kColor(200, 200, 200, 1) forState:UIControlStateNormal];
                self.vipBtn = rightBtn;
                [rightBtn addTarget:self action:@selector(clickedVipBtn) forControlEvents:UIControlEventTouchUpInside];
            }
            
            CGFloat imageWidth = rightBtn.imageView.bounds.size.width;
            CGFloat labelWidth = rightBtn.titleLabel.bounds.size.width;
            rightBtn.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth);
            rightBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWidth-10, 0, imageWidth + 10);
            
            UIView *line = [[UIView alloc] initWithFrame:SARectMake(20, StatusHeight + i * 38 + 37, kBaseScreenWidth - 40, 1)];
            line.backgroundColor = kLineColor;
            [self.view addSubview:line];
        }
        
        if (i == 3) {
            UITextField *remarkTf = [[UITextField alloc] initWithFrame:SARectMake(0, 7, 249, 30)];
            remarkTf.placeholder = @"请输入备注";
            remarkTf.text = @"";
            remarkTf.font = kFont(15);
            remarkTf.clearButtonMode = UITextFieldViewModeWhileEditing;
            remarkTf.frame = SARectMake(kBaseScreenWidth - 270, StatusHeight + i * 38, 250, 37);
            remarkTf.textAlignment = NSTextAlignmentRight;
            self.remarkTf = remarkTf;
            [self.view addSubview:remarkTf];
        }
    }
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelBtn setImage:[UIImage imageNamed:@"btn_cancle"] forState:UIControlStateNormal];
    cancelBtn.frame = SARectMake(kBaseScreenWidth - 37, StatusHeight + 2 * 38, 30, 37);
    cancelBtn.backgroundColor = [UIColor whiteColor];
    [cancelBtn addTarget:self action:@selector(clickedCancelBtn) forControlEvents:UIControlEventTouchUpInside];
    cancelBtn.hidden = YES;
    self.cancelBtn = cancelBtn;
    [self.view addSubview:cancelBtn];
    
    UIView *whiteView2 = [[UIView alloc] initWithFrame:CGRectMake(0, whiteView.maxY + kScaleNum(7), kScreenWidth, kScaleNum(37))];
    whiteView2.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:whiteView2];
    
    UILabel *shopLab = [[UILabel alloc] initWithFrame:SARectMake(20, 0, 150, 37)];
    shopLab.text = @"选择商品";
    shopLab.textColor = kBlackColor;
    shopLab.font = kFont(15);
    [whiteView2 addSubview:shopLab];
    self.shopLab = shopLab;
    
    UILabel *shopPirceLab = [[UILabel alloc] initWithFrame:SARectMake(kBaseScreenWidth - 190, 0, 170, 37)];
    shopPirceLab.textColor = kBlackColor;
    shopPirceLab.text = @"";
    shopPirceLab.font = kFont(15);
    shopPirceLab.textAlignment = NSTextAlignmentRight;
    [whiteView2 addSubview:shopPirceLab];
    self.shopPirceLab = shopPirceLab;
    
    self.tableViewTop = whiteView2.maxY;
    [self.view addSubview:self.tableView];
    
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - kScaleNum(110) - SafeFooterHeight, kScreenWidth, kScaleNum(110) + SafeFooterHeight)];
    footView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:footView];
    footView.hidden = YES;
    self.footView = footView;
    
    NSArray *titleArr = @[@"总金额",@"结算方式"];
    for (int i = 0; i < titleArr.count; i++) {
        UILabel *lab = [[UILabel alloc] initWithFrame:SARectMake(20, i * 35, 100, 35)];
        lab.text = titleArr[i];
        lab.font = kFont(15);
        lab.textColor = kBlackColor;
        [footView addSubview:lab];
        if (i == 3) {
            lab.textColor = kLightgGrayColor;
        }else {
            UIView *line = [[UIView alloc] initWithFrame:SARectMake(0, 34 + i * 35, kBaseScreenWidth, 1)];
            line.backgroundColor = kLineColor;
            [footView addSubview:line];
        }
    }
    
    UILabel *totalCountLab = [[UILabel alloc] initWithFrame:SARectMake(kBaseScreenWidth - 210, 0, 190, 35)];
    totalCountLab.font = kFont(15);
    totalCountLab.textColor = kBlackColor;
    totalCountLab.textAlignment = NSTextAlignmentRight;
    [footView addSubview:totalCountLab];
    self.totalCountLab = totalCountLab;
    
    UIButton *payTypeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    payTypeBtn.frame = SARectMake(kBaseScreenWidth - 210, 35, 190, 35);
    [payTypeBtn setImage:[UIImage imageNamed:@"Sale_rightArrow"] forState:UIControlStateNormal];
    [payTypeBtn setTitle:@"现金" forState:UIControlStateNormal];
    [payTypeBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
    payTypeBtn.titleLabel.font = kFont(15);
    [payTypeBtn addTarget:self action:@selector(showPayTypeView) forControlEvents:UIControlEventTouchUpInside];
    CGFloat imageWidth = payTypeBtn.imageView.bounds.size.width;
    CGFloat labelWidth = payTypeBtn.titleLabel.bounds.size.width;
    payTypeBtn.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth);
    payTypeBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWidth-10, 0, imageWidth + 10);
    payTypeBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [footView addSubview:payTypeBtn];
    self.payTypeBtn = payTypeBtn;
    
    UIButton *settlementBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    settlementBtn.frame = CGRectMake(0, kScaleNum(70), kScreenWidth, kScaleNum(40) + SafeFooterHeight);
    [settlementBtn setBackgroundImage:[UIImage imageNamed:@"top_image"] forState:UIControlStateNormal];
    [settlementBtn setTitle:@"结账" forState:UIControlStateNormal];
    settlementBtn.titleLabel.font = kFont(18);
    [settlementBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [settlementBtn addTarget:self action:@selector(unisversalButtonAcrion:) forControlEvents:UIControlEventTouchUpInside];
    [footView addSubview:settlementBtn];
    self.settlementBtn = settlementBtn;
    
    UIButton *scanBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [scanBtn setImage:[UIImage imageNamed:@"Sale_scan"] forState:UIControlStateNormal];
    scanBtn.frame = CGRectMake(kScaleNum(76), whiteView2.maxY + kScaleNum(10), kScaleNum(53), kScaleNum(52));
    scanBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [scanBtn addTarget:self action:@selector(clickedScanBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:scanBtn];
    self.scanBtn = scanBtn;
    
    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [addBtn setImage:[UIImage imageNamed:@"Sale_Add"] forState:UIControlStateNormal];
    addBtn.frame = CGRectMake(kScreenWidth - kScaleNum(120), whiteView2.maxY + kScaleNum(10), kScaleNum(53), kScaleNum(52));
    addBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [addBtn addTarget:self action:@selector(clickedAddBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:addBtn];
    self.addBtn = addBtn;
    
    [self.view addSubview:self.moreView];
    
    self.systemEmpDetailAPI.empId = model.empId;
    [self.systemEmpDetailAPI sendRequestToServerWithActivityViewAndMask:GET];
    
    [self.systemSettingsListAPI sendRequestToServerWithActivityViewAndMask:GET];
}

#pragma mark - lazy
-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.tableViewTop, kScreenWidth, kScaleNum(200)) style:UITableViewStylePlain];
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        }
        _tableView.backgroundColor = kBgColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        [_tableView registerClass:[SACommodityWarehousingCell class] forCellReuseIdentifier:@"SACommodityWarehousingCell"];
        [_tableView registerClass:[SACommodityWarehousingHeaderView class] forHeaderFooterViewReuseIdentifier:@"SACommodityWarehousingHeaderView"];
    }
    return _tableView;
}

-(UIView *)headerView {
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScaleNum(35))];
        
        UIView *whireView2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScaleNum(35))];
        whireView2.backgroundColor = kTextBgColor;
        [_headerView addSubview:whireView2];
        
        UILabel *titleLab2 = [[UILabel alloc] initWithFrame:SARectMake(20, 0, 35, 35)];
        titleLab2.text = @"商品";
        titleLab2.textColor = kGrayColor;
        titleLab2.font = kBFont(14);
        [whireView2 addSubview:titleLab2];
        
        UILabel *titleLab3 = [[UILabel alloc] initWithFrame:SARectMake(151, 0, 60, 35)];
        titleLab3.text = @"数量";
        titleLab3.textColor = kGrayColor;
        titleLab3.font = kBFont(14);
        titleLab3.textAlignment = NSTextAlignmentCenter;
        [whireView2 addSubview:titleLab3];
        
        UILabel *titleLab4 = [[UILabel alloc] initWithFrame:SARectMake(235, 0, 70, 35)];
        titleLab4.text = @"单价";
        titleLab4.textColor = kGrayColor;
        titleLab4.font = kBFont(14);
        titleLab4.textAlignment = NSTextAlignmentCenter;
        [whireView2 addSubview:titleLab4];
        
        UILabel *titleLab5 = [[UILabel alloc] initWithFrame:SARectMake(305, 0, 70, 35)];
        titleLab5.text = @"小计";
        titleLab5.textColor = kGrayColor;
        titleLab5.font = kBFont(14);
        titleLab5.textAlignment = NSTextAlignmentCenter;
        [whireView2 addSubview:titleLab5];
    }
    return _headerView;
}

-(UIView *)moreView {
    if (!_moreView) {
        _moreView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
        _moreView.backgroundColor = kColor(0, 0, 0, 0.3);
        _moreView.hidden = YES;
        _moreView.userInteractionEnabled = YES;
        
        UIImageView *imageV = [[UIImageView alloc] init];
        imageV.frame = SARectMake(260, StatusHeight + 144, 95, 179);
        imageV.frame = CGRectMake(kScaleNum(260), kScreenHeight -  kScaleNum(219) - SafeFooterHeight, kScaleNum(95), kScaleNum(179));
        imageV.backgroundColor = [UIColor whiteColor];
        [_moreView addSubview:imageV];
        imageV.userInteractionEnabled = YES;
        
        NSArray *btnArr = @[@"现金", @"刷卡", @"汇款", @"微信", @"支付宝"];
        for (int i = 0; i < btnArr.count; i++) {
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.frame = SARectMake(0, 36 * i, 95, 35);
            [btn setTitle:btnArr[i] forState:UIControlStateNormal];
            [btn setTitle:btnArr[i] forState:UIControlStateSelected];
            [btn setTitleColor:kBlackColor forState:UIControlStateNormal];
            [btn setTitleColor:kBuleColor forState:UIControlStateSelected];
            btn.titleLabel.font = kFont(15);
            [btn setAdjustsImageWhenHighlighted:NO];
            [btn addTarget:self action:@selector(clickedPayBtn:) forControlEvents:UIControlEventTouchUpInside];
            btn.tag = 1 + i;
            [imageV addSubview:btn];
            
            if (i < btnArr.count - 1) {
                UIView *line = [[UIView alloc] initWithFrame:SARectMake(0, 35 + 36 * i, 95, 1)];
                line.backgroundColor = kLineColor;
                [imageV addSubview:line];
            }
            
            if (i == 0) {
                self.selectBtn = btn;
                self.selectBtn.selected = YES;
            }
        }
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeView)];
        [_moreView addGestureRecognizer:tap];
    }
    return _moreView;
}

-(NSMutableArray<SASalesOrderViewListModel *> *)dataMarr {
    if (!_dataMarr) {
        _dataMarr = [NSMutableArray array];
    }
    return _dataMarr;
}

-(SASystemSettingsListAPI *)systemSettingsListAPI {
    if (!_systemSettingsListAPI) {
        _systemSettingsListAPI = [SASystemSettingsListAPI apiWithDelegate:self];
    }
    return _systemSettingsListAPI;
}

-(SAWarehousePurchaseSaveAPI *)warehousePurchaseSaveAPI {
    if (!_warehousePurchaseSaveAPI) {
        _warehousePurchaseSaveAPI = [SAWarehousePurchaseSaveAPI apiWithDelegate:self];
        _warehousePurchaseSaveAPI.isPromptErrorMessage = NO;
    }
    return _warehousePurchaseSaveAPI;
}

-(SASystemEmpDetailAPI *)systemEmpDetailAPI {
    if (!_systemEmpDetailAPI) {
        _systemEmpDetailAPI = [SASystemEmpDetailAPI apiWithDelegate:self];
    }
    return _systemEmpDetailAPI;
}

-(SAWarehousePurchaseFindProductAPI2 *)warehousePurchaseFindProductAPI {
    if (!_warehousePurchaseFindProductAPI) {
        _warehousePurchaseFindProductAPI = [SAWarehousePurchaseFindProductAPI2 apiWithDelegate:self];
    }
    return _warehousePurchaseFindProductAPI;
}

-(SAWarehousePurchaseFindProductV2API *)warehousePurchaseFindProductV2API {
    if (!_warehousePurchaseFindProductV2API) {
        _warehousePurchaseFindProductV2API = [SAWarehousePurchaseFindProductV2API apiWithDelegate:self];
    }
    return _warehousePurchaseFindProductV2API;
}

- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

@end
